package ServerNetwork
{
	import Interfaces.MIAppStarter;
	
	import XMFramework.Core.JSONPaser;
	import XMFramework.Interface.IFramework;
	
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.external.ExternalInterface;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.net.URLRequestHeader;
	import flash.net.URLRequestMethod;
	import flash.system.Capabilities;

	public class ApplicationLog		
	{
		private static var _networkRequestLog : Array	=	new Array();
		private static var _networkResponseLog : Array	=	new Array();
		
		private static var _browserId:String			=	null;
		
		private static const LCODE_logAppLoadedSucceeded:String		=	"1";
		private static const LCODE_logAppInitSucceeded:String		=	"2";
		private static const LCODE_logAppServerInitSucceeded:String	=	"3";
		private static const LCODE_logAppError:String				=	"4";
		private static const LCODE_logTutorialProgess:String		=	"5";
		private static const LCODE_logAppUnrecoveryError:String		=	"6";		
		private static const LCODE_logStartAppServerInit:String		=	"7";
		private static const LCODE_logBattleTutorialProgess:String	=	"8";
		
		public static function networkRequestLog( msgId : int, callId : int, params : Array ) : void
		{
			var log : Object			=	new Object();
			log["msgId"]				=	msgId;
			log["callId"]				=	callId;
			log["params"]				=	params;
			_networkRequestLog.push( log );
		}
		
		public static function networkResponseLog( msgId : int, callId : int, params : * ) : void
		{
			var log : Object			=	new Object();
			log["msgId"]				=	msgId;
			log["callId"]				=	callId;
			log["params"]				=	params;
			_networkResponseLog.push( log );
		}
		
		public static function getNetworkLogStr( lastCount : int = int.MAX_VALUE ) : String
		{
			var result : String	=	"";
			
			var data : Array	=	getNetworkLogArray( lastCount );
			result	=	JSONPaser.serialize( data );
			
			return result;
		}
		
		public static function getNetworkLogIds( sns_message : Object, lastCount : int = int.MAX_VALUE ) : Array
		{
			var result : Array	=	new Array();
			
			var index : int		=	_networkRequestLog.length-1;
			for( var count : int=0; count<lastCount; count++ )
			{
				if( index < 0 )
					break;			
				
				result.push( getMsgString(_networkRequestLog[index].msgId) );				
				index--;
			}
			
			return result.reverse();
			
			function getMsgString( msg : String) : String
			{
				for( var i:String in sns_message )
				{
					if( sns_message[i] == msg )
						return i + "[" + msg + "]";
				}
				
				return msg;
			}
		}
		
		public static function getNetworkLogArray( lastCount : int = int.MAX_VALUE, includeData : Boolean = false ) : Array
		{
			var result : Array	=	new Array();
			
			var index : int		=	_networkRequestLog.length-1;
			for( var count : int=0; count<lastCount; count++ )
			{
				if( index < 0 )
					break;
				
				var requestData : Object	=	_networkRequestLog[index];
				
				var session : Array	=	new Array();
				
				session["request"]	=	new Array();
				session["request"]["msgId"]				=	requestData.msgId;
				
				if( includeData )
				{
					session["request"]["callId"]			=	requestData.callId;
					session["request"]["params"]		=	requestData.params;
				}
				
				session["response"]			=	new Array();
				var responceData : Object	=	getResponceData( requestData.callId );
				if( responceData != null )
				{
					session["response"]["msgId"]		=	responceData.msgId;
					
					if( includeData )
					{
						session["response"]["callId"]		=	responceData.callId;
						session["response"]["params"]		=	responceData.params;
					}
				}
				
				if( includeData )
					session["callId"]			=	requestData.callId;
					
				result.push( session );
				
				index--;
			}
			
			return result;
			
			function getResponceData( callId : int ) : Object
			{
				for( var i:int=0; i<_networkResponseLog.length; i++ )
				{
					if( _networkResponseLog[i].callId == callId )
						return _networkResponseLog[i];
				}
				
				return null;
			}
		}
		
		public static function logAppLoadedSucceeded( root:MIAppStarter ):void
		{
			var socialParams : Object	=	root.getSocialParams();
			var url:String				=	socialParams["externalLog"];
			var userId:String			=	socialParams["uid"];
			var newUser:String			=	socialParams["isNewPlayer"];
			
			if( newUser == false )
				return;	
			
			if( url == null || url.length == 0 )
				return;
			
			try
			{				
				var request: URLRequest	=	new URLRequest();
				request.url 			=	url+"?code="+LCODE_logAppLoadedSucceeded+"&userid="+userId+"&agent="+getUserAgent()+"&fpver="+Capabilities.version+"&os="+Capabilities.os+"&time="+socialParams["bootrapTime"]+"&msg=empty";
				request.contentType 	= 	'application/octet-stream';
				request.method 			= 	URLRequestMethod.POST;
				request.requestHeaders.push( new URLRequestHeader( 'Cache-Control', 'no-cache' ) );
				
				var loader:URLLoader 	= 	new URLLoader();
				loader.dataFormat 		= 	URLLoaderDataFormat.TEXT;
				loader.addEventListener(IOErrorEvent.IO_ERROR, dummyErrorHandle);
				loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, dummyErrorHandle);

				loader.load( request );
			}
			catch(ex:*){}
		}
		
		public static function logAppInitSucceeded( coreSNSFramework:IFramework ):void
		{
			var root:MIAppStarter		=	coreSNSFramework.globalHolder.getVariable( ShareMacros.VAR_APP_ROOT ) as MIAppStarter;
			var socialParams : Object	=	root.getSocialParams();
			var url:String				=	socialParams["externalLog"];
			var userId:String			=	socialParams["uid"];
			var newUser:String			=	socialParams["isNewPlayer"];
			
			if( newUser == false )
				return;	
			
			if( url == null || url.length == 0 )
				return;
			
			try
			{
				var request: URLRequest	=	new URLRequest();
				request.url 			=	url+"?code="+LCODE_logAppInitSucceeded+"&userid="+userId+"&agent="+getUserAgent()+"&fpver="+Capabilities.version+"&os="+Capabilities.os+"&time="+coreSNSFramework.timer.tickingServerTime+"&msg=empty";
				request.contentType 	= 	'application/octet-stream';
				request.method 			= 	URLRequestMethod.POST;
				request.requestHeaders.push( new URLRequestHeader( 'Cache-Control', 'no-cache' ) );
				
				var loader:URLLoader 	= 	new URLLoader();
				loader.dataFormat 		= 	URLLoaderDataFormat.TEXT;
				loader.addEventListener(IOErrorEvent.IO_ERROR, dummyErrorHandle);
				loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, dummyErrorHandle);
				loader.load( request );
			}
			catch(ex:*){}
		}
		
		public static function logAppServerInitSucceeded( coreSNSFramework:IFramework ):void
		{
			var root:MIAppStarter		=	coreSNSFramework.globalHolder.getVariable( ShareMacros.VAR_APP_ROOT ) as MIAppStarter;
			var socialParams : Object	=	root.getSocialParams();
			var url:String				=	socialParams["externalLog"];
			var userId:String			=	socialParams["uid"];
			var newUser:String			=	socialParams["isNewPlayer"];
		
			if( newUser == false )
				return;
		
			if( url == null || url.length == 0 )
				return;
			
			try
			{				
				var request: URLRequest	=	new URLRequest();
				request.url 			=	url+"?code="+LCODE_logAppServerInitSucceeded+"&userid="+userId+"&agent="+getUserAgent()+"&fpver="+Capabilities.version+"&os="+Capabilities.os+"&time="+coreSNSFramework.timer.tickingServerTime+"&msg=empty";
				request.contentType 	= 	'application/octet-stream';
				request.method 			= 	URLRequestMethod.POST;
				request.requestHeaders.push( new URLRequestHeader( 'Cache-Control', 'no-cache' ) );
				
				var loader:URLLoader 	= 	new URLLoader();
				loader.dataFormat 		= 	URLLoaderDataFormat.TEXT;
				loader.addEventListener(IOErrorEvent.IO_ERROR, dummyErrorHandle);
				loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, dummyErrorHandle);
				loader.load( request );
			}
			catch(ex:*){}
		}
		
		public static function logStartAppServerInit( coreSNSFramework:IFramework ):void
		{
			var root:MIAppStarter		=	coreSNSFramework.globalHolder.getVariable( ShareMacros.VAR_APP_ROOT ) as MIAppStarter;
			var socialParams : Object	=	root.getSocialParams();
			var url:String				=	socialParams["externalLog"];
			var userId:String			=	socialParams["uid"];
			var newUser:String			=	socialParams["isNewPlayer"];
			
			if( newUser == false )
				return;
			
			if( url == null || url.length == 0 )
				return;
			
			try
			{				
				var request: URLRequest	=	new URLRequest();
				request.url 			=	url+"?code="+LCODE_logStartAppServerInit+"&userid="+userId+"&agent="+getUserAgent()+"&fpver="+Capabilities.version+"&os="+Capabilities.os+"&time="+coreSNSFramework.timer.tickingServerTime+"&msg=empty";
				request.contentType 	= 	'application/octet-stream';
				request.method 			= 	URLRequestMethod.POST;
				request.requestHeaders.push( new URLRequestHeader( 'Cache-Control', 'no-cache' ) );
				
				var loader:URLLoader 	= 	new URLLoader();
				loader.dataFormat 		= 	URLLoaderDataFormat.TEXT;
				loader.addEventListener(IOErrorEvent.IO_ERROR, dummyErrorHandle);
				loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, dummyErrorHandle);
				loader.load( request );
			}
			catch(ex:*){}
		}
		
		public static function logAppError( coreSNSFramework:IFramework, msgId:String ):void
		{
			var root:MIAppStarter		=	coreSNSFramework.globalHolder.getVariable( ShareMacros.VAR_APP_ROOT ) as MIAppStarter;
			var socialParams : Object	=	root.getSocialParams();
			var url:String				=	socialParams["externalLog"];
			var userId:String			=	socialParams["uid"];
						
			if( url == null || url.length == 0 )
				return;
			
			try
			{				
				var request: URLRequest	=	new URLRequest();
				request.url 			=	url+"?code="+LCODE_logAppError+"&userid="+userId+"&agent="+getUserAgent()+"&fpver="+Capabilities.version+"&os="+Capabilities.os+"&time="+coreSNSFramework.timer.tickingServerTime+"&msg="+msgId;
				request.contentType 	= 	'application/octet-stream';
				request.method 			= 	URLRequestMethod.POST;
				request.requestHeaders.push( new URLRequestHeader( 'Cache-Control', 'no-cache' ) );
				
				var loader:URLLoader 	= 	new URLLoader();
				loader.dataFormat 		= 	URLLoaderDataFormat.TEXT;
				loader.addEventListener(IOErrorEvent.IO_ERROR, dummyErrorHandle);
				loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, dummyErrorHandle);
				loader.load( request );
			}
			catch(ex:*){}
		}
		
		public static function logAppUnrecoveryError( coreSNSFramework:IFramework, msgId:String ):void
		{
			var root:MIAppStarter		=	coreSNSFramework.globalHolder.getVariable( ShareMacros.VAR_APP_ROOT ) as MIAppStarter;
			var socialParams : Object	=	root.getSocialParams();
			var url:String				=	socialParams["externalLog"];
			var userId:String			=	socialParams["uid"];
			
			if( url == null || url.length == 0 )
				return;
			
			try
			{				
				var request: URLRequest	=	new URLRequest();
				request.url 			=	url+"?code="+LCODE_logAppUnrecoveryError+"&userid="+userId+"&agent="+getUserAgent()+"&fpver="+Capabilities.version+"&os="+Capabilities.os+"&time="+coreSNSFramework.timer.tickingServerTime+"&msg="+msgId;
				request.contentType 	= 	'application/octet-stream';
				request.method 			= 	URLRequestMethod.POST;
				request.requestHeaders.push( new URLRequestHeader( 'Cache-Control', 'no-cache' ) );
				
				var loader:URLLoader 	= 	new URLLoader();
				loader.dataFormat 		= 	URLLoaderDataFormat.TEXT;
				loader.addEventListener(IOErrorEvent.IO_ERROR, dummyErrorHandle);
				loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, dummyErrorHandle);
				loader.load( request );
			}
			catch(ex:*){}
		}
		
		public static function logTutorialProgess( coreSNSFramework:IFramework, progressId:String ):void
		{
			var root:MIAppStarter		=	coreSNSFramework.globalHolder.getVariable( ShareMacros.VAR_APP_ROOT ) as MIAppStarter;
			var socialParams : Object	=	root.getSocialParams();
			var url:String				=	socialParams["externalLog"];
			var userId:String			=	socialParams["uid"];
			var newUser:String			=	socialParams["isNewPlayer"];
			
			if( newUser == false )
				return;	
			
			if( url == null || url.length == 0 )
				return;
			
			try
			{				
				var request: URLRequest	=	new URLRequest();
				request.url 			=	url+"?code="+LCODE_logTutorialProgess+"&userid="+userId+"&agent="+getUserAgent()+"&fpver="+Capabilities.version+"&os="+Capabilities.os+"&time="+coreSNSFramework.timer.tickingServerTime+"&msg="+progressId;
				request.contentType 	= 	'application/octet-stream';
				request.method 			= 	URLRequestMethod.POST;
				request.requestHeaders.push( new URLRequestHeader( 'Cache-Control', 'no-cache' ) );
				
				var loader:URLLoader 	= 	new URLLoader();
				loader.dataFormat 		= 	URLLoaderDataFormat.TEXT;
				loader.addEventListener(IOErrorEvent.IO_ERROR, dummyErrorHandle);
				loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, dummyErrorHandle);
				loader.load( request );
			}
			catch(ex:*){}
		}
		
		public static function logBattleTutorialProgess( coreSNSFramework:IFramework, progressId:String ):void
		{
			trace("TutorialBattle : " + progressId);
			var root:MIAppStarter		=	coreSNSFramework.globalHolder.getVariable( ShareMacros.VAR_APP_ROOT ) as MIAppStarter;
			var socialParams : Object	=	root.getSocialParams();
			var url:String				=	socialParams["externalLog"];
			var userId:String			=	socialParams["uid"];

			
			if( url == null || url.length == 0 )
				return;
			
			try
			{				
				var request: URLRequest	=	new URLRequest();
				request.url 			=	url+"?code="+LCODE_logBattleTutorialProgess+"&userid="+userId+"&agent="+getUserAgent()+"&fpver="+Capabilities.version+"&os="+Capabilities.os+"&time="+coreSNSFramework.timer.tickingServerTime+"&msg="+progressId;
				request.contentType 	= 	'application/octet-stream';
				request.method 			= 	URLRequestMethod.POST;
				request.requestHeaders.push( new URLRequestHeader( 'Cache-Control', 'no-cache' ) );
				
				var loader:URLLoader 	= 	new URLLoader();
				loader.dataFormat 		= 	URLLoaderDataFormat.TEXT;
				loader.addEventListener(IOErrorEvent.IO_ERROR, dummyErrorHandle);
				loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, dummyErrorHandle);
				loader.load( request );
			}
			catch(ex:*){}
		}
		
		private static function dummyErrorHandle( event:Event ):void
		{ 
			event.preventDefault(); 
			event.stopImmediatePropagation();
		}
		
		private static function getUserAgent():String
		{ 
			if( _browserId == null )
			{
				try
				{				
					var userAgent:String = ExternalInterface.call("window.navigator.userAgent.toString");
					_browserId = "[Unknown Browser]";
					
					//if (userAgent.indexOf("Safari") != -1)
					//	_browserId = "Safari";
					
					if (userAgent.indexOf("Firefox") != -1)
						_browserId = "Firefox";
					
					else if (userAgent.indexOf("Chrome") != -1)
						_browserId = "Chrome";
					
					else if (userAgent.indexOf("MSIE") != -1)
						_browserId = "Internet Explorer";
					
					else if (userAgent.indexOf("Opera") != -1)
						_browserId = "Opera";
				}
				catch (e:*){}
			}
						
			return _browserId;
		}
	}
}